﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using TCL.DB;
using TCL.EO;

namespace TCL.FUNC
{
    public class Logs
    {
        public Boolean WriteLog_To_DB(LogEO objLog, Boolean isLogForDB)
        {
            try
            {
                if (isLogForDB)
                {
                    if (!StringEx.Equals(SystemEx.getAppSettings("NMT_isWriteLog", ConstEx.appSetting_State.Default), ConstEx.appSetting_State.Open))
                        return false;
                    objLog.tTimeEnd = DateTime.Now;
                    objLog.dProcessTime = (objLog.tTimeEnd - objLog.tTimeBegin).TotalMilliseconds;
                }
                (new ShareDAO.LogDAO(false)).Log_InsertItem(objLog);
                return true;
            }
            catch (Exception ex)
            {
                WriteLog_To_File(ex.ToString());
                return false;
            }
        }

        public void WriteLog_To_File(String strEX)
        {
            try
            {
                LogEO objLog = new LogEO(strEX, 000);
                String sRoot = SystemEx.getAppSettings("NMT_RawUrl_RootPath", "C:\\") + "Logs\\";
                String sContent = ConvertEx.JsonEx.Object_2_Json(objLog);
                if (!Directory.Exists(sRoot))
                {
                    Directory.CreateDirectory(sRoot);
                }
                String sPathTemp = Folder_File.getFullFolder(sRoot, objLog.iType) + Folder_File.getFileNameByDateTime(ConstEx.Log_iType_NameFile_DateTime_C.Default);
                FileInfo fInfo = new FileInfo(sPathTemp);
                if (!fInfo.Exists)
                {
                    using (StreamWriter sw = File.AppendText(sPathTemp))
                    {
                        sw.Close();
                    }
                }
                else
                {
                    if (fInfo.Length > 2097152) // Check file log > 2MB = 2097152
                        fInfo.MoveTo(Folder_File.getFullFolder(sRoot, objLog.iType) + Folder_File.getFileNameByDateTime(ConstEx.Log_iType_NameFile_DateTime_C.Second));
                }
                using (StreamWriter sw = File.AppendText(sPathTemp))
                {
                    sw.WriteLine(sContent + ",");
                    sw.Close();
                }
            }
            catch { }
        }

        public List<LogEO> ReadLog_From_File(String sPath, ref String sContent)
        {
            List<LogEO> lstLogEO = new List<LogEO>();
            try
            {
                if (!String.IsNullOrEmpty(sPath))
                {
                    sContent = StringEx.TrimEx(System.IO.File.ReadAllText(sPath));
                    if (!sContent.StartsWith("["))
                        sContent = "[" + sContent;
                    if (sContent.EndsWith(","))
                        sContent = sContent.Remove(sContent.Length - 1);
                    if (!sContent.EndsWith("]"))
                        sContent = sContent + "]";
                    lstLogEO = new List<LogEO>();
                    lstLogEO = (List<LogEO>)ConvertEx.JsonEx.Json_2_ListObject<LogEO>(sContent, lstLogEO.GetType());
                    lstLogEO = lstLogEO.OrderByDescending(x => x.tTimeBegin).ToList();
                }
            }
            catch (Exception ex)
            {
                (new Logs()).WriteLog_To_DB(new LogEO(ex.ToString(), ConstEx.Log_iType.EXCEPTION), false);
            }
            return lstLogEO;
        }

        public String WriteLog_File_To_DB(Boolean isSQL, String strItemPath)
        {
            try
            {
                String sContent = "";
                SortedList stlLog = new SortedList();
                if (String.IsNullOrEmpty(strItemPath))
                {
                    strItemPath = SystemEx.getAppSettings("NMT_RawUrl_RootPath") + "Logs\\";
                    stlLog = Folder_File.getListFileInFolder(strItemPath);
                }
                else
                {
                    stlLog.Add(strItemPath, strItemPath);
                }
                foreach (String itemFile in stlLog.Keys)
                {
                    List<LogEO> lstLog = ReadLog_From_File(itemFile, ref sContent);
                    if (isSQL)
                    {
                        DataTable dt = ConvertEx.ConvertListObjectToDataTable(lstLog);
                        using (var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["connMSSql"].ConnectionString, SqlBulkCopyOptions.KeepIdentity))
                        {
                            bulkCopy.BulkCopyTimeout = 600;
                            bulkCopy.DestinationTableName = "tblLog";
                            bulkCopy.WriteToServer(dt);
                        }
                    }
                    else
                    {
                        foreach (var itemLog in lstLog)
                        {
                            (new ShareDAO.LogDAO()).LogOther_InsertItem(itemLog);
                        }
                    }
                    File.Delete(itemFile);
                }
                return String.Empty;
            }
            catch (Exception ex)
            {
                (new Logs()).WriteLog_To_DB(new LogEO(ex.ToString(), ConstEx.Log_iType.EXCEPTION), false);
                return ex.ToString();
            }
        }
    }
}
